<!-- 通知公告 -->
<template>
  <div class="module_ news">
    <div class="mb8">
      <search @clearSearch='clearSearch'>
        <el-form label-width='50px' inline autocomplete="off"  :model="pageparm" class="search_box">
          <el-form-item label="标题">
            <el-input size="medium" clearable v-model="pageparm.title" placeholder="请输入标题搜索"/>
          </el-form-item>
          <!-- <el-form-item label="姓名">
            <inputSearch ref="search_e" placeholder="请输入发布人姓名搜索" @onChange='searchChane($event,"sender_id")'  />
          </el-form-item>  -->
        </el-form>
        <template class="flex" slot="footer">
          <el-button class="mr8" size="medium" type="primary" @click="handle()">发布消息</el-button>
        </template>
      </search>
    </div>
    <el-table
      :data="tableData"
      height="100%"
      size="medium"
      border
      highlight-current-row
      v-loading="tableLoading"
      @sort-change="tableSortChange"
      @row-click='newsInfo'
      :row-class-name="setBgColor">
      <el-table-column
        align="center"
        prop="title"
        label="标题"
        min-width="400"
        sortable="custom">
      </el-table-column>
      <!-- <el-table-column
        align="center"
        prop="review_status"
        label="状态"
        min-width="160"
        sortable="custom"
        show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.review_status === 2" class="c-red">{{reviewStatusObj[scope.row.review_status]}}：{{scope.row.review_comment}}</span>
          <span v-else>{{reviewStatusObj[scope.row.review_status]}}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        align="center"
        prop="sender_id"
        label="发布人"
        width="150"
        sortable="custom"
        show-overflow-tooltip>
        <template slot-scope="scope">
          {{scope.row.employee?scope.row.employee.name:''}}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="created_at"
        label="发布时间"
        width="200"
        sortable="custom"
        show-overflow-tooltip>
      </el-table-column>
      <el-table-column
        align="center"
        prop="read"
        label="已读人数"
        width="140">
      </el-table-column>
      <el-table-column
        align="center"
        prop="proportion_read"
        label="已读人数占比"
        width="140">
      </el-table-column>
      <el-table-column
        align="center"
        prop="is_top"
        label="是否置顶"
        width="120"
        sortable="custom">
        <template slot-scope="scope">
          <span>{{scope.row.is_top === 1 ? '已置顶' : '未置顶'}}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="130">
        <div class="tx-c" slot-scope="scope">
          <!-- <el-tooltip  effect="dark" content="审核" placement="bottom-end" v-show="scope.row.review_status == 0">
            <el-button  v-permission="{action:'消息管理审核',effect:'delete'}" type="primary" @click.stop="examine_btns(scope.row,1)" size="small"  icon="el-icon-help" circle></el-button>
          </el-tooltip> -->
          <el-tooltip effect="dark" :content="scope.row.is_top === 2? '置顶':'取消置顶'" placement="bottom-end">
            <el-button
              size="small"
              @click.stop="isTop(scope.row)"
              :icon="scope.row.is_top === 2? 'el-icon-upload2':'el-icon-download'"
              circle
            ></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="bottom-end">
            <el-button
              size="small"
              type="danger"
              @click.stop="deleteUser(scope.$index, scope.row)"
              icon="el-icon-delete"
              circle
            ></el-button>
          </el-tooltip>
        </div>
      </el-table-column>
    </el-table>

    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>

    <el-dialog
      class="dialog"
      :visible.sync="editFormVisible"
      width="800px"
      @click="editFormVisible = false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close='dialogClose'
      top="10vh">
      <h2 slot="title" class="tx-c fb">
        发布消息
      </h2>
      <el-form autocomplete="off"  label-width="90px" label-position="left" :model="editForm" class="content" >
        <el-form-item label="标题：" class="tip">
          <el-input type="text" v-model="editForm.title" size="medium" placeholder="请输入标题" clearable></el-input>
        </el-form-item>
        <wangeditor ref="wangeditor" @getContent="getContent" />
        <el-form-item label="附件">
          <!-- accept=".xls,.doc,.txt,.pdf,.xls,.csv,.docx,.pptx" -->
          <el-upload
            multiple
            action="/"
            :on-change='onChangeFile'
            :on-remove="onRemoveFile"
            :auto-upload="false"
            ref="upload"
            :file-list='fileList'>
            <el-button size="medium" type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="接收类型" class="tip">
          <el-radio-group v-model="editForm.send_type" @change="sendType">
            <el-radio :label="1">按角色发送</el-radio>
            <el-radio :label="2">按人员发送</el-radio>
            <el-radio :label="3">全部</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="tip" label="接收人" v-if="editForm.send_type === 2" >
          <multipleSearch :options="{type:'message'}" @onChange="choseList" />
        </el-form-item>
        <el-form-item class="tip" label="接收角色" v-else-if="editForm.send_type === 1">
          <multipleSearch :options="{type:'message'}" type='role' ref="roles" @onChange="choseList" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="flex-justify-bcenter">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
    <articleDialog ref="articleDialog" :info='articleInfo' :showSend='true' />

    <!-- 审核 -->
    <examine ref="examine" @submit='examineSubmit' />
  </div>
</template>

<script>
import {
  Apimessagemanage,
  ApimessagemanageAdd,
  ApimessagemanageDel,
  ApimessagemanageTop,
  ApimessagemanageCheck
} from "@/api";
import { debounce,adminShow} from "@/utils";
import multipleSearch from '@/components/multipleSearch'
import wangeditor from '@/components/wangeditor'
import articleDialog from "../components/articleDialog.vue"
import {reviewStatusObj} from '@/assets/js'

export default {
  components:{
    multipleSearch,
    wangeditor,
    articleDialog
  },
  data() {
    return {
      adminShow: adminShow(),
      reviewStatusObj,
      tableData: [],
      editFormVisible: false,
      editForm: {
        title:'',
        content: '',
        send_type: null
      }, //修改
      pageparm: {
        page: 1,
        perPage: 20,
        total: null,
        sort_str: null,
        sort_order: null,
      },
      tableLoading: false,

      fileList:[],

      sendList:[],

      articleInfo:{
        employee:{}
      },//文章详情

      examine_id: null,  //审核id
      examine_item:{
        
      }
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    setBgColor(row){
      if(row.row.is_top === 1){
        return 'istopstyle'
      }
    },
    examineSubmit(options){
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      options.id = this.examine_id
      ApimessagemanageCheck(options,options.id).then(res => {
        this.getList()
      }).catch(()=>{
        this.$message.error('服务器错误，请重新提交');   
      }).finally(()=>{
        loading.close()
      })
    },
    examine_btns(item,i){
      this.examine_id = item.id
      if(i > 1){
        this.examine_item.review_status = item.review_status
        this.examine_item.review_comment = item.review_comment
        this.examine_item.view = true
      }else{
        // this.examine_item.review_status = null
        // this.examine_item.review_comment = null
        this.examine_item.view = false
      }
      this.$refs.examine.examineShow = true

    },
    newsInfo(item){
      this.articleInfo = item
      this.$refs.articleDialog.showArticle = true
    },
    isTop(val){
      let options = {}
      if(val.is_top === 2) options.is_top = 1
      else options.is_top = 2
      ApimessagemanageTop(options,val.id).then(res =>{
        this.getList()
      }).catch(()=>{
        this.$message.error('操作失败');
      })
    },
    dialogClose(){
      this.editForm =  {
        title:'',
        content: '',
        send_type: null
      }
      this.$refs.wangeditor.clear()
      this.fileList = []
      this.sendList = []
    },
    getContent(html){
      this.editForm.content = html
    },
    choseList(list){
      this.sendList = list
    },
    sendType(i){
      if( i === 1){
        this.$refs.roles.getRoles()
      }
    },
    onChangeFile(file, fileList){
      this.fileList.push(file)
    },
    onRemoveFile(file, fileList){
      this.fileList = fileList
    },
    searchChane(i,val){
      this.pageparm[val] = i
      this.pageparm.page = 1
      this.getList()
    },
    handle(index, item, i) {
      this.editFormVisible = true;
    },
    tableSortChange(column) {
      if (column.order === "descending") {
        this.pageparm.sort_str = column.prop;
        this.pageparm.sort_order = "desc";
      } else if (column.order === "ascending") {
        this.pageparm.sort_str = column.prop;
        this.pageparm.sort_order = "asc";
      } else {
        this.pageparm.sort_str = null;
        this.pageparm.sort_order = null;
      }
      if (column.prop.includes(".")) {
        this.pageparm.sort_str = 'sub_' + column.prop.split(".")[0] + "s_id";
      }
      this.getList();
    },
    //搜索
    clearSearch(){
      this.$refs.search_e.clear()
    },

    //分页
    callFather(pageparm) {
      this.pageparm.page = pageparm.page;
      this.pageparm.perPage = pageparm.perPage;
      this.getList();
    },
    getList() {
      this.tableLoading = true;
      Apimessagemanage(this.pageparm)
        .then(({ data, page }) => {
          this.tableData = data || [];
          this.pageparm.total = page.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    deleteUser(index, value) {
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: "删除中...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          ApimessagemanageDel(value.id)
            .then((res) => {
              this.getList(true);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            })
            .finally(() => {
              loading.close();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    submit: debounce(
      function () {
        //提交  修改或新增
        const editForm = this.editForm ;
        if(!this.editForm.title){
          this.$message.error('请输入标题');
          return
        }
        if(!this.editForm.content){
          this.$message.error('请输入内容');
          return
        }
        if(!this.editForm.send_type){
          this.$message.error('请选择发送方式');
          return
        }
        if(this.editForm.send_type !== 3 && this.sendList.length === 0){
          this.$message.error('请选择接收人或接收角色');
          return
        }
        const loading = this.$loading({
          lock: true,
          text: "加载中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        const formData = new FormData()
        formData.append('sender_id',this.$store.state.userInfo.employees_id)
        formData.append('title',editForm.title)
        formData.append('content',editForm.content)
        formData.append('send_type',editForm.send_type)
        if(this.fileList.length > 0){
          this.fileList.forEach(item=>{
            formData.append('attachment[]',item.raw)
          })
        }
        if(editForm.send_type !== 3 ){
          this.sendList.forEach(item => {
            if(editForm.send_type === 1){
              formData.append('roles_id[]',item)
            }else if(editForm.send_type === 2){
              formData.append('employees_id[]',item)
            }
          })
        }
        ApimessagemanageAdd(formData,{
            headers:{'Content-Type':'multipart/form-data'}
        }).then(res => {
          this.$message({
            type: "success",
            message: "发布成功!",
          });
          this.editFormVisible = false;
          this.getList();
        }).catch(()=>{
          this.$message({
            type: "error",
            message: "发布失败!",
          });
        }).finally(() => {
            loading.close();
        })},
      500,
      true
    ),
  },
};
</script>

<style lang='less'>
.news{
  .content{
    .el-input,.el-textarea__inner{
      width: 500px;
    }
  }
}

</style>